#!/bin/bash
# description: gaea Start Stop Restart
# processname: gaea
# chkconfig: 234 10 90

echo `date` >> /data/br/bin/result.txt

systemctl start docker

containers=(`docker inspect --format='{{.Name}}' $(docker ps -aq --no-trunc) | cut -c2- | awk -F "+" '{for(i=1;i<=NF;i++) a[i,NR]=$i}END{for(i=1;i<=NF;i++) {for(j=1;j<=NR;j++) printf a[i,j] " ";print ""}}'`)

temp_containers=( "mysql" "redis" "zk" "kafka" "hadoop" "druid" "zeus" "nacos" "service" )

start_hadoop_process(){
	hdfs_process="journalnode namenode zkfc datanode"
	yarn_process="resourcemanager nodemanager"
	historyserver_process=historyserver
	all_process=(${hdfs_process} ${yarn_process} ${historyserver_process})
	hadoop_process=(`ls /data/br/logs/hadoop | awk -F '-' '{print $3}' | uniq | awk -F "+" '{for(i=1;i<=NF;i++) a[i,NR]=$i}END{for(i=1;i<=NF;i++) {for(j=1;j<=NR;j++) printf a[i,j] " ";print ""}}'`)
	for(( m=0;m<${#all_process[@]};m++))
	do
		for(( n=0;n<${#hadoop_process[@]};n++))
		do
			if [[ ${hadoop_process[$n]} =~ ${all_process[$m]} ]]
			then
				if [[ ${hdfs_process} =~ ${all_process[$m]} ]]
				then
					echo ${all_process[$m]}
					docker exec -u 2048 -i br-hadoop hadoop-daemons.sh start ${all_process[$m]}
				elif [[ ${yarn_process} =~ ${all_process[$m]} ]]
				then
					echo ${all_process[$m]}
					docker exec -u 2048 -i br-hadoop yarn-daemon.sh start ${all_process[$m]}
				else
					echo ${all_process[$m]}
					docker exec -u 2048 -i br-hadoop mr-jobhistory-daemon.sh start ${all_process[$m]}
				fi
			fi
		done
	done
}

start_containers(){
	for(( i=0;i<${#temp_containers[@]};i++))
	do
			for(( j=0;j<${#containers[@]};j++))
			do
					if [[ ${containers[$j]} =~ ${temp_containers[$i]} ]]
					then
						if [[ "hadoop" =~ ${temp_containers[$i]} ]]
						then
							docker start ${containers[$j]}
							start_hadoop_process
						else
							docker start ${containers[$j]}
						fi
					fi
			done
			echo "-----${temp_containers[$i]}-----"	>> /data/br/bin/result.txt
	done

    sleep 60
	docker start ${containers[@]}
}

case $1 in
        start)
                start_containers
                ;;
        stop)
                echo 'gaea stop' >> /data/br/bin/result.txt
                ;;
        restart)
                echo 'gaea restart' >> /data/br/bin/result.txt
                ;;
        *)
                echo 'please use : tomcat {start | stop | restart}'
        ;;
esac
exit 0